package com.player.thirdGroup.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

public class DownloadAndUpload {
	/**
	 * 文件下载 
	 * 文件名：filename 
	 * 请求：request
	 * 响应：response
	 */
	public static void fileDownLoad2(String filename, HttpServletRequest request,
			HttpServletResponse response)  {
		// 设置文件的MiMe类型
		response.setContentType(request.getServletContext().getMimeType(
				filename));
		// 设置content-dispsition
		response.setHeader("Content-Disposition", "attachment;filename="
				+ filename);
		// 读取目标文件，通过response将目标文件写到客户端
		String fullName = request.getServletContext().getRealPath(
				"/img/" + filename);
		try {
			// 读取文件
			InputStream in = new FileInputStream(fullName);
			OutputStream out = response.getOutputStream();
			// 写文件
			int b = 0;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 文件下载： 
	 * 服务器请求：request 
	 * 下载文件名：fileName
	 */
	public static ResponseEntity<byte[]> fileDownLoad1(
			HttpServletRequest request, String fileName) {
		// 文件存储路径名
		String realPath;
		// 输入流
		InputStream inputStream;
		// 输入流读取字节
		byte[] body = null;
		// 响应头
		HttpHeaders headers;
		// 响应码
		HttpStatus statusCode;
		// ResponseEntity 表示整个HTTP响应:状态代码,标题和正文
		ResponseEntity<byte[]> response;

		// 获取文件存储路径
		realPath = request.getServletContext().getRealPath("/img/" + fileName);
		// 将该文件加入到输入流之中
		try {
			inputStream = new FileInputStream(new File(realPath));

			// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取（或跳过）的估计剩余字节数
			body = new byte[inputStream.available()];
			// 读入到输入流里面
			inputStream.read(body);

			// 防止中文乱码
			fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 设置响应头
		headers = new HttpHeaders();

		headers.add("Content-Disposition", "attachment;filename=" + fileName);

		// 设置响应码
		statusCode = HttpStatus.OK;
		// 响应
		response = new ResponseEntity<byte[]>(body, headers, statusCode);
		return response;
	}

	/**
	 * 文件上传： 
	 * 上传的文件：myfile 
	 * 服务器请求：request 
	 * 返回文件名：fileName
	 */
	public static String fileUpload(MultipartFile myfile,
			HttpServletRequest request) {
		// 文件存储路径名
		String realPath;
		// 上传文件名
		String originalFilename;
		// 存储UUID
		String uuid;
		// 存储文件后缀名的下标
		int lastIndexOf;
		// 存储 UUID加后缀的文件名
		String fileName;
		// 获得文件所在的绝对路径
		String filepath;
		// 文件对象
		File file;

		// 获取文件存储路径
		realPath = request.getServletContext().getRealPath("/img");
		System.out.println(realPath);
		// 获取上传文件名字
		originalFilename = myfile.getOriginalFilename();
		// UUID拼接
		uuid = UUID.randomUUID().toString();
		lastIndexOf = originalFilename.lastIndexOf(".");
		fileName = originalFilename.substring(lastIndexOf);
		fileName = uuid + fileName;
		System.out.println(fileName);
		// 获得文件所在的绝对路径
		filepath = realPath + "\\" + fileName;
		// 创建文件对象
		file = new File(filepath);
		try {
			// 上传文件
			myfile.transferTo(file);
		} catch (IllegalStateException | IOException e) {
			System.out.println("上传失败");
			e.printStackTrace();
		}
		return fileName;
	}
}
